package com.example.mes_sys.jwt;

import com.example.mes_common.exception.BusinessException;
import com.example.mes_sys.security.CustomUserDetailsService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;

/**
 * JWT 认证过滤器，用于拦截请求并验证 JWT
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Autowired
    private JwtTokenProvider tokenProvider;

    @Autowired
    private CustomUserDetailsService userService;

    // 从请求头中获取 Token
    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("token");
        if (StringUtils.hasText(bearerToken)) {
            return bearerToken;
        }
        return null;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String path = request.getRequestURI();
        logger.debug("JwtFilter processing request for path: {}", path);
        try {
            // 1. 从请求头中获取 JWT
            String jwt = getJwtFromRequest(request);

            // 2. 验证 JWT 是否有效
            if (StringUtils.hasText(jwt) && tokenProvider.valiLocalDateTimeToken(jwt)) {
                // 3. 从 JWT 中获取用户 ID
                Long userId = tokenProvider.getUserIdFromJWT(jwt);

                // 4. 加载用户信息
                UserDetails userDetails = userService.loadUserById(userId);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                // 5. 设置认证信息到 SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception ex) {
            logger.error("Could not set user authentication in security context", ex);
            throw new BusinessException("Could not set user authentication in security context");
        }

        filterChain.doFilter(request, response);
    }
}
